import 'package:audio_video_progress_bar/audio_video_progress_bar.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:oss_upload/oss_upload.dart';
import 'package:richedit/data/audio_entity.dart';
import 'package:richedit/loading_widget.dart';
import 'package:richedit/res/color.dart';
import 'package:richedit/widget/audio_player_widget.dart';

class AudioEdit extends StatefulWidget {
  AudioEntity data;

  AudioEdit(this.data);

  @override
  _AudioEditState createState() => _AudioEditState();
}

class _AudioEditState extends State<AudioEdit> {
  int _uploadCount = 0;
  int _uploadTotal = 0;
  bool _isUpload = false;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () async {
          LoadingWidget.showLoading(context, text: "正在读取文件");
          FilePickerResult? result = await FilePicker.platform.pickFiles(
            type: FileType.audio,
            allowedExtensions: [],
          );

          LoadingWidget.dismissLoading();
          if (result == null) {
            return;
          }
          var uploadFile = await OSSUpload.uploadFile(result.files.single.path!,"1", "1", "1", suffix: ".mp3",
              onSendProgress: (int count, int total) {
            _uploadCount = count;
            _uploadTotal = total;
            _isUpload = true;
            setState(() {});
          });
          _isUpload = false;
          if (uploadFile != null) {
            String fileUrl = uploadFile['url'];
            widget.data.url = fileUrl;
            setState(() {});
          }
        },
        child: Container(
          child: widget.data.url == null
              ? Container(
                  width: 80,
                  height: 80,
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.black12, width: 1),
                  ),
                  child: _isUpload
                      ? Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text("${(_uploadCount * 100 / _uploadTotal).toStringAsFixed(1)}%"),
                            Padding(padding: const EdgeInsets.all(4)),
                            Text("正在上传"),
                          ],
                        )
                      : Icon(Icons.radio),
                )
              : Container(
                  padding: const EdgeInsets.all(1),
                  constraints: BoxConstraints(
                    maxHeight: 300,
                  ),
                  child: AudioShow(widget.data.url!),
                ),
        ),
      ),
    );
  }
}

class AudioPreview extends StatefulWidget {
  AudioEntity data;

  AudioPreview(this.data);

  @override
  _AudioPreviewState createState() => _AudioPreviewState();
}

class _AudioPreviewState extends State<AudioPreview> {
  @override
  Widget build(BuildContext context) {
    var alignment;
    if (widget.data.align == "2") {
      alignment = Alignment.centerRight;
    } else if (widget.data.align == "1") {
      alignment = Alignment.center;
    } else {
      alignment = Alignment.centerLeft;
    }
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 8),
      child: Align(
        alignment: alignment,
        child: FractionallySizedBox(
          widthFactor: widget.data.full == 1 ? 1 : 0.5,
          child: Column(
            children: [
              AudioShow(widget.data.url!, isFull: widget.data.full == 1,),
              widget.data.text != null
                  ? Center(
                      child: Text(
                        widget.data.text??"",
                        style: TextStyle(fontSize: 13, color: Colour.text_3),
                      ),
                    )
                  : Container(),
            ],
          ),
        ),
      ),
    );
  }
}

class AudioShow extends StatefulWidget {
  final String audioPath;
  final bool isFull;

  const AudioShow(this.audioPath, {this.isFull = true});

  @override
  _AudioShowState createState() => _AudioShowState();
}

class _AudioShowState extends State<AudioShow> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 46,
      margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(30),
        color: Colour.bg_7,
      ),
      child: AudioPlayerWidget(audioUrl: widget.audioPath, location: widget.isFull ? TimeLabelLocation.sides : TimeLabelLocation.none,),
    );

  }

  @override
  void dispose() {
    super.dispose();
  }
}

class AudioSetting extends StatefulWidget {
  AudioEntity data;
  ValueChanged onChanged;

  AudioSetting(this.data, this.onChanged);

  @override
  _AudioSettingState createState() => _AudioSettingState();
}

class _AudioSettingState extends State<AudioSetting> {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.only(topLeft: Radius.circular(8), topRight: Radius.circular(8)),
        color: Colors.white,
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            children: [
              Text("大小："),
              sizeWidget("1"),
              sizeWidget("0"),
            ],
          ),
          Row(
            children: [
              Text("对齐："),
              alignWidget("0"),
              alignWidget("1"),
              alignWidget("2"),
            ],
          ),
        ],
      ),
    );
  }

  Widget sizeWidget(String full) {
    String sizeStr;
    if (full == 0) {
      sizeStr = "一半";
    } else {
      sizeStr = "铺满";
    }
    return GestureDetector(
      onTap: () {
        widget.data.full = full;
        setState(() {
          widget.onChanged(widget.data);
        });
      },
      child: Container(
        width: 36,
        height: 36,
        margin: const EdgeInsets.all(5),
        decoration: BoxDecoration(
          border: Border.all(color: Colors.blue, width: widget.data.full == full ? 2 : 1),
        ),
        child: Center(child: Text(sizeStr)),
      ),
    );
  }

  Widget alignWidget(String align) {
    String alignStr;
    if (align == "0") {
      alignStr = "居左";
    } else if (align == "1") {
      alignStr = "居中";
    } else {
      alignStr = "居右";
    }
    return GestureDetector(
      onTap: () {
        widget.data.align = align;
        setState(() {
          widget.onChanged(widget.data);
        });
      },
      child: Container(
        width: 36,
        height: 36,
        margin: const EdgeInsets.all(5),
        decoration: BoxDecoration(
          border: Border.all(color: Colors.blue, width: widget.data.align == align ? 2 : 1),
        ),
        child: Center(child: Text(alignStr)),
      ),
    );
  }
}

Future<AudioEntity?> showAudioSetting(BuildContext context, AudioEntity data, ValueChanged onChanged) {
  return showModalBottomSheet<AudioEntity>(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (context) {
        return AudioSetting(data, onChanged);
      });
}
